package com.alibaba.dubbo.common.inet.ipv4;

import java.net.InetAddress;
import java.net.InetSocketAddress;

import com.alibaba.dubbo.common.inet.IPMatcherException;
import com.alibaba.dubbo.common.inet.InetAddressSupport;
import com.alibaba.dubbo.common.inet.InetAddressMatcher;


/**
 * ipv4地址范围
 * 
 * @author kingbo.ruan 2014.09.24
 *
 */
public class RangeMatcher implements InetAddressMatcher {
	protected long from = -1;
	protected long to = -1;
	public RangeMatcher(String from, String to) {
		//this.from  = InetAddressSupport.ipToLong(from);
		//this.to = InetAddressSupport.ipToLong(to);
		if(from == null || to == null) throw new IPMatcherException();
		if(from.equals("*")){
			this.from = 0;
		}
		if(to.equals("*")) {
			this.to =  0xffffffff;
		}
		
		String [] ss = from.split("\\.");
		if(ss.length != 4) throw new IPMatcherException();
		long l = 0;
		for(int i = 0;i< ss.length;i++){
			String n = ss[i].trim();
			Integer t = 0;
			if(n.length() == 0 || n.equals("*")){
			}else{
				t = Integer.parseInt(n, 10);
			}
			if(t < 0 || t > 255)  throw new IPMatcherException();
			l *= 256;
			l += t;
		}
		
		this.from = l;
		
		ss = to.split("\\.");
		if(ss.length != 4) throw new IPMatcherException();
		l = 0;
		for(int i = 0;i< ss.length;i++){
			String n = ss[i].trim();
			Integer t = 255;
			if(n.length() == 0 || n.equals("*")){
			}else{
				t = Integer.parseInt(n, 10);
			}
			if(t < 0 || t > 255)  throw new IPMatcherException();
			l *= 256;
			l += t;
		}
		this.to = l;
	}

	@Override
	public boolean match(InetAddress address) {
		byte [] bytes = address.getAddress();
		long value = InetAddressSupport.ipToLong(bytes);
		return value >= from && value <= to;
	}
	
	@Override
	public InetAddress select(InetAddress[] addresses) {
		for(InetAddress address : addresses){
			if(this.match(address)) return address;
		}
		return null;
	}
}
